import React = require("react");
import { BaseComponent } from "./base-component";

export type Status = "loading" | "complete" | "empty";
export interface State {
    status?: Status
}
export abstract class SpinerComponent<P, S extends State = {}> extends BaseComponent<P, S> {
    abstract loadData(): Promise<Partial<S> | string>;
    private emptyText: string;

    constructor(props: P) {
        super(props);

        let render = this.render;
        console.assert(render != null);
        this.render = () => {
            let { status } = this.state || {} as State;
            status = status || "loading";
            if (status == "loading") {
                return <div className="loading">
                    <i className="icon-spinner icon-spin" style={{ marginRight: 4 }} />
                    <span>数据正在加载中...</span>
                </div>
            }
            else if (status == "empty") {
                let emptyText = this.emptyText || "暂无所要显示的数据"
                return <div className="empty">
                    <span>{emptyText}</span>
                </div>
            }

            return render.apply(this);
        }

        let componentDidMount = this.componentDidMount;
        this.componentDidMount = async () => {
            let s = await this.loadData() as S;

            if (s == null || typeof s == "string") {
                this.emptyText = s as any;
                this.setState({ status: "empty" });

                return;
            }

            s.status = "complete";
            this.setState(s);
            if (componentDidMount)
                componentDidMount.apply(this);
        }
    }

}